/***global.cpp
 *	2011.11.4, liyang
 *	Version 1.0
 *	describes all the global variables
 ***/

#include "global.h"
#include "disposecmd.h"
#include "socket.h"

struct StMemory g_memory;				//shared memory
struct StRecvCmd g_recvcmd[MAXCMD];		//recv cmd
struct StSendMsg g_sendmsg[MAXCMD];		//send msg

extern char g_serialnum[22];							//serianum
extern char g_serverip[17];								//serverip
extern int g_serverport;								//serverport

/***globalInit() brief initialization function
 * 2011.11.4, liyang
 * param void
 *
 * retval, 0 if successful or -1 failed
 * Version 2.0
 ***/
int globalInit()
{
	printf("~~~~~~~~~~~~~~~~~~start init~~~~~~~~~~~~~~~~~~~~~~\n");
	//~~~~~~~~~~initialize struct StRecvCmd and struct StSendCmd~~~~~~~~~~~//
	for (int i=0;i<MAXCMD;i++)
	{
		g_recvcmd[i].cmd[0]='\0';
		g_recvcmd[i].flag=false;
		g_sendmsg[i].msg[0]='\0';
		g_sendmsg[i].flag=false;
		g_sendmsg[i].retrytimes=0;
	}

	//~~~~~~~~~~create  shared map~~~~~~~~~~//
	g_memory.shmFD=open(SHARENAME,O_CREAT|O_RDWR,0777);
	if(-1 == g_memory.shmFD)
	{
		ERROROUT("open file failed!");
		return -1;
	}
	g_memory.shmADDR=(char*)mmap( NULL,SHARESIZE,PROT_READ|PROT_WRITE,MAP_SHARED,g_memory.shmFD,0 );
	if (g_memory.shmADDR == MAP_FAILED)
	{
		ERROROUT("mmap failed!");
		return -1;
	}

	//~~~~~~~~~~get servermsg~~~~~~~~~~~//
	if (-1 == getSerialNum(g_serialnum,g_serverip,g_serverport))
	{
		printf("please set server_ip/port and serialnum first!!\n");
		return -1;
	}
	LOGI("serverip is:%s\n",g_serverip);
	LOGI("serverport is:%d\n",g_serverport);
	LOGI("serialnum is:%s\n",g_serialnum);

	//~~~~~~~~~~create  thread~~~~~~~~~~//
	typedef void*(*format)(void *);													///define function pointer of "void*(name)(void*)"
	pthread_t l_socketlinkthread;													/// the file description of thread
	pthread_attr_t l_attrthread;													///the attribute of thread
	size_t l_stacksize=1048576*1;													///set thread stack size
	///start thread.
	pthread_attr_init(&l_attrthread);												///initialize attribute
	pthread_attr_setscope(&l_attrthread,PTHREAD_SCOPE_SYSTEM);						///set attribute binding
	pthread_attr_setdetachstate(&l_attrthread,PTHREAD_CREATE_DETACHED);				///set attribute detached
	pthread_attr_setstacksize(&l_attrthread,l_stacksize);
	if(-1==pthread_create(&l_socketlinkthread,&l_attrthread,(format)socketHandler,NULL))
	{
		ERROROUT("thread2 create failed!");
		return -1;
	}
	return 0;
}
